﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using umbraco.cms.businesslogic.member;
using System.Web.Security;
using System.Text;

namespace osMemberControls
{
    public partial class MemberForgotPassword : System.Web.UI.UserControl
    {
        private string _userName, _subject;
        private int _redirectID;


        public string UserNameLabel
        {
            get { return _userName; }
            set { _userName = value; }
        }

        public string Subject
        {
            get { return _subject;}
            set {_subject = value;}
        }



        public int RedirectID
        {
            get{ return _redirectID;}
            set {_redirectID = value; }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                lblUserName.Text = UserNameLabel;
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                MailMessage mm = new MailMessage();
                SmtpClient s = new SmtpClient();
                Member m = Member.GetMemberFromLoginName(txtUserName.Text);
                                
                string newPassword = RandomString(8, true);
                m.Password = newPassword;
                m.Save();
            
                
                mm.To.Add(m.Email);
                mm.Subject = Subject;
                mm.Body = "Your new password is " + newPassword;
                mm.Body = mm.Body.Replace("##loginname##", m.LoginName);
                mm.Body = mm.Body.Replace("##email##", m.Email);
                mm.IsBodyHtml = true;

                s.Send(mm);

                Response.Redirect(umbraco.library.NiceUrl(RedirectID));
            }
        }

        private string RandomString(int size, bool lowerCase)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            if (lowerCase)
                return builder.ToString().ToLower();
            return builder.ToString();
        }

    }
}